package com.t194.controller;

import com.t194.entity.Role;
import com.t194.entity.User;
import com.t194.service.RoleService;
import com.t194.util.TreeNode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("/sys/role")
public class RoleController {
    @Resource
    private RoleService roleService;
    private String msg;

    @GetMapping("/index")
    public String index() {
         return "sys/role";
    }
    /*@GetMapping("/queryAll")
    @ResponseBody
    public PageResult queryAll() {
        List<Role> list = roleService.searchAll();
        *//*for (Role role : list) {
            System.out.println(role.getId()+"==>"+role.getCreatedBy());
        }*//*
        //return list;
        System.out.println(list);
        return PageResult.success(list);
    }*/
    @GetMapping("/list")
    //ajax要用ResponseBody
    @ResponseBody
    public List<Role> list() {
        List<Role> list = roleService.searchAll();
        System.out.println(list);
        return list;
    }
    //批量删除
    @GetMapping("/batchDel")
    @ResponseBody
    public String batchDel(Integer[] ids) {
        try {
            roleService.batchDel(ids);
            msg = "删除成功!";
        } catch (Exception ex) {
            ex.printStackTrace();
            msg = "删除失败!";
        }
        return msg;
    }

    /*跳转添加页面*/
    @GetMapping("/add")
    public String add() {
        return "sys/role_add";
    }
    @PostMapping("/add")
    public String add(Role role, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser != null) {
            role.setCreatedBy(loginUser.getId());
        }
        role.setCreationDate(LocalDateTime.now());
        System.out.println("添加前："+role.getId());
        roleService.add(role);
        System.out.println("添加后："+role.getId());
        return "redirect:/sys/role/index";
    }

    //修改
    @PostMapping("/update")
    @ResponseBody
    public String update(Role role, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser != null) {
            role.setModifyBy(loginUser.getId());
        }
        role.setModifyDate(LocalDateTime.now());
        roleService.update(role);
        try {
            roleService.update(role);
            msg = "修改角色成功！";
        } catch (Exception ex) {
            msg = "修改角色失败！";
        }
        return msg;
    }

    @GetMapping("/query4Tree")
    @ResponseBody
    public List<TreeNode> query4Tree() {
        return roleService.search4Tree();
    }
}
